package com.boang.controller;

import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.SaLoginConfig;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.boang.convert.SysUserConvert;
import com.boang.entity.po.SysUser;
import com.boang.entity.req.LoginReq;
import com.boang.entity.resp.LoginRes;
import com.boang.service.SysUserService;
import com.boang.service.impl.CaptchaService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 13813
 */
@Tag(name = "用户登录", description = "用户登录相关")
@RestController
public class LoginController {

    @Resource
    SysUserService sysUserService;

    @Resource
    private SysUserConvert sysUserConvert;

    @Resource
    private CaptchaService captchaService;

    @Operation(summary = "用户登录")
    @PostMapping("/doLogin")
    public SaResult doLogin(@Validated @RequestBody LoginReq loginReq) {

        // 判断验证码是否正确
        if (!captchaService.validateCaptcha(loginReq.getCode())) {
            return SaResult.error("验证码错误");
        }

        //根据用户名查询用户信息
        SysUser user = sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserName, loginReq.getUserName()));

        // assert(条件语句)，如果条件语句为真，继续往下执行，如果为假就会报错
        Assert.notNull(user, "用户不存在");
        Assert.isTrue(BCrypt.checkpw(loginReq.getPassword(), user.getPassword()), "密码错误");

        // 校验指定账号是否已被封禁，如果被封禁则抛出异常 `DisableServiceException`
        StpUtil.checkDisable(user.getUserId());
        // 通过校验后，再进行登录
        StpUtil.login(user.getUserId(), SaLoginConfig.setExtra("name", user.getUserName()));

        // entity数据转为vo响应的数据
        LoginRes loginRes = sysUserConvert.toLoginRes(user);

        //设置 token
        loginRes.setToken(StpUtil.getTokenValue());

        return SaResult.data(loginRes);
    }

    @GetMapping("isLogin")
    public SaResult isLogin() {
        return SaResult.ok("是否登录：" + StpUtil.isLogin());
    }

    @GetMapping("tokenInfo")
    public SaResult tokenInfo() {
        return SaResult.data(StpUtil.getTokenInfo());
    }

    @GetMapping("logout")
    public SaResult logout() {
        StpUtil.logout();
        return SaResult.ok();
    }
}




